package com.summer.springboot.mybatisplus.multiple.config;

import cn.hutool.core.util.StrUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Order(0)
@Aspect
@Component
@Slf4j
public class DsAspect {

    @Pointcut("execution(* com.summer.springboot.mybatisplus.multiple..service..*Service.*(..))")
    public void dataSourcePointCut() {

    }

    @Before("dataSourcePointCut()")
    public void before(JoinPoint joinPoint) {
        if(StrUtil.isNotBlank(DbContextHolder.getCurrentDsStr())) {
            log.info("current thread {} use datasource[{}]", Thread.currentThread().getName(), DbContextHolder.getCurrentDsStr());
            return;
        }
        String methodName = joinPoint.getSignature().getName();
        Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
        try {
            if(null != method &&method.isAnnotationPresent(DS.class)){
                DS td = method.getAnnotation(DS.class);
                String dbStr = td.value();
                DbContextHolder.setCurrentDsStr(dbStr);
                log.info("current thread {} add dataSource [{}]", Thread.currentThread().getName(), dbStr);
            }else {
                DbContextHolder.setCurrentDsStr(DbContextHolder.getDefaultDs());
                log.info("user default dataSource[{}]", DbContextHolder.getDefaultDataSource());
            }

        }catch (Exception e) {
            log.error("case datasource err");
        }
    }

    @After("dataSourcePointCut()")
    public void after(JoinPoint joinPoint) {
        DbContextHolder.clearCurrentDsStr();
    }

}
